//
//  collectViewController.m
//  LastTemp
//
//  Created by apple on 15/4/28.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "collectViewController.h"
#import "BassModel.h"
#import "AVSingleton.h"
#import "AFSoundManager.h"
#import "bofangViewController.h"

@interface collectViewController ()
@property(nonatomic,retain)NSMutableArray *allArr;
@property(nonatomic,copy)NSString *songStr;
@property(nonatomic,copy)NSString *urlStr;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,retain)NSMutableArray *songArr;

@property(nonatomic,retain)UIImageView *imageVIew;
@property(nonatomic,assign)BOOL isWobble;
@end

@implementation collectViewController

- (void)dealloc
{
    [_allArr release];
    [_songArr release];
    [_tableView release];
    [_imageVIew release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.allArr = [NSMutableArray array];
        self.songArr = [NSMutableArray array];
        self.isWobble = NO;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [_tableView release];
    [self sql];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shanchu"] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    

}

- (void)rightClick:(UIBarButtonItem *)button
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"删除所有收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *button = [alertView buttonTitleAtIndex:buttonIndex];
    if ([button isEqualToString:@"确定"]) {
        
        //        NSLog(@"hahaha");
        //开启数据库
        NSArray *sandArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *sandPath = [sandArr lastObject];
        NSString *dbPath = [sandPath stringByAppendingPathComponent:@"music.sqlite"];
        NSLog(@"%@",dbPath);
        int result = sqlite3_open([dbPath UTF8String], &dbPoint);
        if (result == SQLITE_OK) {
            //            NSLog(@"数据库开启成功");
        }else{
            //            NSLog(@"数据库开启失败");
        }
        
        //创建表
        NSString *sqlStr = @"create table if not exists music(number integer primary key autoincrement,song_name text,singer_name text,url text)";
        int result2 = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
        if (result2 == SQLITE_OK) {
            //            NSLog(@"创建表成功");
        }else{
            //            NSLog(@"创建表失败");
        }
        // 删除表
        NSString *dropTableSQL = [NSString stringWithFormat:@"drop table music"];
        int result3 = sqlite3_exec(dbPoint, [dropTableSQL UTF8String], nil, nil, nil);
        if (result3 == SQLITE_OK) {
            //            NSLog(@"成功");
        } else {
            //            NSLog(@"失败");
        }
       [self showMessage:@"删除成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)showMessage:(NSString *)message
{
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-75, self.view.frame.size.height/2-32.5, 150, 65)];
    view2.backgroundColor = [UIColor whiteColor];
    view2.alpha = 0.8;
    UILabel *label = [[UILabel alloc] init];
    label.text = message;
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(view2.frame.size.width/2-50, view2.frame.size.height/2-20, 100, 40);
    [view2 addSubview:label];
    
    [self.view addSubview:view2];
    [UIView animateWithDuration:2 animations:^{
        view2.alpha = 0;
    } completion:^(BOOL finished) {
        [view2 removeFromSuperview];
    }];
    
    [label release];
    [view2 release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.songArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:str] autorelease];
    }
    BassModel *base = self.songArr[indexPath.row];
    cell.textLabel.text = base.name1;
    cell.detailTextLabel.text = base.singerName1;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BassModel *base = self.songArr[indexPath.row];
    
    if ([AVSingleton shareSingleton].fromNum != indexPath.row || [AVSingleton shareSingleton].fromNum != 0) {
        [[AFSoundManager sharedManager] stop];
    }
    [[AFSoundManager sharedManager] startStreamingRemoteAudioFromURL:base.url1 andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
        [AVSingleton shareSingleton].percentage = percentage;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"mm:ss"];
        NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
        [AVSingleton shareSingleton].beginTime = [formatter stringFromDate:elapsedTimeDate];
        
        NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
        [AVSingleton shareSingleton].time = [formatter stringFromDate:timeRemainingDate];
        
        
    }];
    
    
    [AVSingleton shareSingleton].fromArr = self.songArr;
    [AVSingleton shareSingleton].fromNum = indexPath.row;
    [AVSingleton shareSingleton].myBool = YES;
    bofangViewController *play = [[bofangViewController alloc] init];
    [self presentViewController:play animated:YES completion:^{
        
    }];
    [play release];
   
}







-(void)sql
{
    //开启数据库
    NSArray *sandArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sandPath = [sandArr lastObject];
    NSString *dbPath = [sandPath stringByAppendingPathComponent:@"music.sqlite"];
    NSLog(@"%@",dbPath);
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"数据库开启成功");
    }else{
        NSLog(@"数据库开启失败");
    }
    
    //创建表
    NSString *sqlStr = @"create table if not exists music(number integer primary key autoincrement,song_name text,singer_name text,url text)";
    int result2 = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result2 == SQLITE_OK) {
        NSLog(@"创建表成功");
    }else{
        NSLog(@"创建表失败");
    }
    
    // 查询数据库内所有内容
 
    NSString *selectAll = @"select *from music";
    sqlite3_stmt *stmt= nil;
    int result3 = sqlite3_prepare(dbPoint, [selectAll UTF8String], -1, &stmt, nil);
    if (result3 == SQLITE_OK) {
        NSLog(@"查询成功");
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *song_name = sqlite3_column_text(stmt, 1);
            const unsigned char *singer_name = sqlite3_column_text(stmt, 2);
            const unsigned char *url = sqlite3_column_text(stmt, 3);
            NSString *song = [NSString stringWithUTF8String:(const char *)song_name];
            NSString *singername = [NSString stringWithUTF8String:(const char *)singer_name];
            NSString *songUrl = [NSString stringWithUTF8String:(const char *)url];
            BassModel *base = [[BassModel alloc] init];
            base.name1 = song;
            base.singerName1 = singername;
            base.url1 = songUrl;
            [self.songArr addObject:base];
        }
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
